package com.hfstu.framework.util;



import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.StringTokenizer;

/**
 * 读properities工具类
 * 
 * @author dejunx
 * 
 */
public class PropertiesHelper {

	private static PropertiesHelper ph = null;
	private static final String propertiesName = "hw.properties";
	private static final Map<String, Properties> allProperties = new HashMap<String, Properties>();

	private PropertiesHelper(String propName) {
		init(propName);

	}

	private void init(String propName) {
		try {

			Properties currentProp = getProperties(propName);
			if (currentProp == null) {
				propName = (propName == null || "".equals(propName)) ? propertiesName
						: propName;
				InputStream is = FileInputStreamUtil.getFileInputStream(
						PropertiesHelper.class, propName);
				Properties p = new Properties();
				p.load(is);
				allProperties.put(propName, p);
			}

		} catch (Exception e) {
			e.printStackTrace();

		}
	}

	public Properties getProperties(String propName) {
		String key = propertiesName;
		if (propName == null || "".equals(propName)) {
			key = propertiesName;
		} else {
			key = propName.trim();
		}
		Properties p = (Properties) allProperties.get(key);
		return p;
	}

	/**
	 * 得到该类的实例
	 * 
	 * @param propName
	 *            properties文件名 如果为null 则默认读取hw.properties
	 * @return
	 */
	public synchronized static PropertiesHelper getInstance(String propName) {
		if (ph == null) {
			ph = new PropertiesHelper(propName);
		} else {
			ph.init(propName);
		}
		return ph;
	}

	public synchronized String getProperty(String propName, String key) {
		String value = null;
		Properties currentProp = getProperties(propName);
		if (currentProp != null) {
			value = currentProp.getProperty(key);
		}
		return value;
	}

	public synchronized List<String> getProperties(String propName, String key) {
		List<String> results = new ArrayList<String>();
		Properties currentProp = getProperties(propName);
		if (currentProp != null) {
			String values = currentProp.getProperty(key);
			StringTokenizer st = new StringTokenizer(values, ",");
			while (st.hasMoreElements()) {
				results.add(st.nextToken().trim());
			}
		}
		return results;
	}

	public static void main(String[] args) {
		PropertiesHelper ph = PropertiesHelper.getInstance(null);

		System.out.println(ph.getProperty(null, "EMAIL_ATTACH_TEMP"));

		PropertiesHelper ph1 = PropertiesHelper.getInstance("db.properties");

		System.out.println(ph1 == ph);

		System.out.println(ph1.getProperty("db.properties", "drivers"));

		PropertiesHelper ph2 = PropertiesHelper.getInstance(null);

		System.out.println(ph2 == ph1);

		System.out.println(ph2.getProperty(null, "EMAIL_ATTACH_TEMP"));
	}
}
